package com.maiyuren.fishkit.ui.components

import android.os.Build
import androidx.annotation.RequiresApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

data class FishMenuItem(
    val title: String,
    val icon: String? = null,
    val iconSize: TextUnit = 18.sp,
    val param: Any? = null,
    val onClick: (data: FishMenuItem)->Unit
)

@RequiresApi(Build.VERSION_CODES.Q)
@Composable
fun FishMenu(
    modifier: Modifier = Modifier,
    data: List<FishMenuItem>,
    offset: DpOffset = DpOffset(0.dp, 0.dp),
    visible: MutableState<Boolean>
) {
    DropdownMenu(
        modifier = modifier
            .background(MaterialTheme.colorScheme.background),
        expanded = visible.value,
        offset = offset,
        onDismissRequest = { visible.value = false }
    ) {
        data.forEachIndexed { index, value->
            DropdownMenuItem(
                modifier = Modifier.height(30.dp),
                text = @Composable {
                    Row {
                        if (value.icon != null) {
                            FishIconButton(icon = value.icon, fontSize = value.iconSize, padding = PaddingValues(end = 8.dp, start = 0.dp, bottom = 0.dp, top = 0.dp)) {
                                visible.value = false
                                value.onClick(value)
                            }
                        }
                        Text(
                            modifier = Modifier.padding(0.dp),
                            text = value.title,
                            color = MaterialTheme.colorScheme.onPrimary,
                        )
                    }
                },
                onClick = {
                    visible.value = false
                    value.onClick(value)
                })
        }
    }
}